package com.rlz.base.util.livedata

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import android.os.Build
import androidx.lifecycle.LiveData
import com.rlz.base.app.Base

/**
 * Created by RLZ
 * on 2021/5/13
 * 监听网路变化
 */
class NetWorkLiveData private constructor(): LiveData<Boolean>() {

    private val mNetReceiver: NetReceiver = NetReceiver()
    private val mCallback: NetCallback = NetCallback()


    companion object {
        val instance: NetWorkLiveData by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            NetWorkLiveData()
        }
    }

    @SuppressLint("MissingPermission")
    override fun onActive() {
        super.onActive()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val manager = Base.obtain().getSystemService(
                    Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            manager.requestNetwork(NetworkRequest.Builder().build(), mCallback)
        } else
            Base.obtain().registerReceiver(mNetReceiver,
                    IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
    }

    @SuppressLint("ObsoleteSdkInt")
    override fun onInactive() {
        super.onInactive()
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Base.obtain().unregisterReceiver(mNetReceiver)
        }
    }


    @SuppressLint("MissingPermission", "NewApi", "WrongConstant")
    private class NetReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            instance.postValue((context?.getSystemService(
                    Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo!!.isConnected)
        }
    }


    @SuppressLint("MissingPermission", "NewApi", "WrongConstant")
    private class NetCallback : ConnectivityManager.NetworkCallback() {
        override fun onLost(network: Network) {
            super.onLost(network)
            instance.postValue(false)
        }

        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            instance.postValue(true)
        }
    }
}